import { defineStore } from 'pinia'
import { diaryApi } from '@/api'

export const useDiaryStore = defineStore('diary', {
  state: () => ({
    // 日记列表
    diaryList: [],
    // 当前日记详情
    currentDiary: null,
    // 分页信息
    pagination: {
      page: 1,
      pageSize: 10,
      total: 0
    },
    // 加载状态
    loading: false,
    // 查询参数
    queryParams: {
      keyword: '',
      startDate: '',
      endDate: '',
      location: ''
    }
  }),

  getters: {
    // 获取日记总数
    totalDiaries: (state) => state.pagination.total,

    // 获取当前页日记
    currentPageDiaries: (state) => state.diaryList,

    // 是否有更多数据
    hasMore: (state) => {
      const { page, pageSize, total } = state.pagination
      return page * pageSize < total
    },

    // 根据ID获取日记
    getDiaryById: (state) => (id) => {
      return state.diaryList.find(diary => diary.id === id) || state.currentDiary
    }
  },

  actions: {
    // 获取日记列表
    async getDiaryList(params = {}) {
      try {
        this.loading = true
        const queryParams = { ...this.queryParams, ...params }
        const response = await diaryApi.getDiaryList(queryParams)

        if (response.code === 200) {
          this.diaryList = response.data.list || []
          this.pagination = {
            page: response.data.page || 1,
            pageSize: response.data.pageSize || 10,
            total: response.data.total || 0
          }
        }
      } catch (error) {
        console.error('获取日记列表失败:', error)
        this.diaryList = []
      } finally {
        this.loading = false
      }
    },

    // 获取日记详情
    async getDiaryDetail(id) {
      try {
        this.loading = true
        const response = await diaryApi.getDiaryDetail(id)

        if (response.code === 200) {
          this.currentDiary = response.data
          return { success: true, data: response.data }
        } else {
          return { success: false, message: response.message || '获取日记详情失败' }
        }
      } catch (error) {
        console.error('获取日记详情失败:', error)
        return { success: false, message: error.message || '获取日记详情失败' }
      } finally {
        this.loading = false
      }
    },

    // 创建日记
    async createDiary(diaryData) {
      try {
        this.loading = true
        const response = await diaryApi.createDiary(diaryData)

        if (response.code === 200) {
          // 添加到列表顶部
          this.diaryList.unshift(response.data)
          this.pagination.total += 1
          return { success: true, data: response.data, message: '创建成功' }
        } else {
          return { success: false, message: response.message || '创建失败' }
        }
      } catch (error) {
        console.error('创建日记失败:', error)
        return { success: false, message: error.message || '创建失败' }
      } finally {
        this.loading = false
      }
    },

    // 更新日记
    async updateDiary(id, diaryData) {
      try {
        this.loading = true
        const response = await diaryApi.updateDiary(id, diaryData)

        if (response.code === 200) {
          // 更新列表中的日记
          const index = this.diaryList.findIndex(diary => diary.id === id)
          if (index !== -1) {
            this.diaryList[index] = response.data
          }

          // 更新当前日记
          if (this.currentDiary && this.currentDiary.id === id) {
            this.currentDiary = response.data
          }

          return { success: true, data: response.data, message: '更新成功' }
        } else {
          return { success: false, message: response.message || '更新失败' }
        }
      } catch (error) {
        console.error('更新日记失败:', error)
        return { success: false, message: error.message || '更新失败' }
      } finally {
        this.loading = false
      }
    },

    // 删除日记
    async deleteDiary(id) {
      try {
        this.loading = true
        const response = await diaryApi.deleteDiary(id)

        if (response.code === 200) {
          // 从列表中移除
          this.diaryList = this.diaryList.filter(diary => diary.id !== id)
          this.pagination.total -= 1

          // 清除当前日记
          if (this.currentDiary && this.currentDiary.id === id) {
            this.currentDiary = null
          }

          return { success: true, message: '删除成功' }
        } else {
          return { success: false, message: response.message || '删除失败' }
        }
      } catch (error) {
        console.error('删除日记失败:', error)
        return { success: false, message: error.message || '删除失败' }
      } finally {
        this.loading = false
      }
    },

    // 上传图片
    async uploadImage(file) {
      try {
        const formData = new FormData()
        formData.append('file', file)

        const response = await diaryApi.uploadImage(formData)

        if (response.code === 200) {
          return { success: true, data: response.data, message: '上传成功' }
        } else {
          return { success: false, message: response.message || '上传失败' }
        }
      } catch (error) {
        console.error('上传图片失败:', error)
        return { success: false, message: error.message || '上传失败' }
      }
    },

    // 设置查询参数
    setQueryParams(params) {
      this.queryParams = { ...this.queryParams, ...params }
    },

    // 重置查询参数
    resetQueryParams() {
      this.queryParams = {
        keyword: '',
        startDate: '',
        endDate: '',
        location: ''
      }
    },

    // 清空当前日记
    clearCurrentDiary() {
      this.currentDiary = null
    }
  }
})
